//
//  ListTableviewModel.m
//  YZZX
//
//  Created by Easaa on 15/4/10.
//  Copyright (c) 2015年 Easaa. All rights reserved.
//

#import "ListTableviewModel.h"

@implementation ListTableviewModel
{
    HXHttpRequest           *_httpRequest;              //发起请求
    HXHttpRequest           *_httpRequest_head;         //发起请求  ---(请求tabbleview 的headview)
                   //数据源
    YZCellMassgeModel       *Cellcellmodel;            //Cell Model
    
    NSInteger               NuBerRefreshing;            //上拉加载页数 初始化为1
    NSString                *CellIdentiferId;           //一般模型的cell的ID
    NSString                *ModelOneCelliId;           //只有title的cell id
    NSString                *ModelTwoCelliId;           //有title和massge 的id
    
    UIView                  *headviewbg;                            //底headview
    UIScrollView            *headView;                              //头view
    UIPageControl           *pageControl;                           //
    NSMutableArray          *headDataArray;                           //head数据
    
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;

}



#pragma mark 设置tableview 的cell 下划线顶格
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}




- (id)initWithFram: (CGRect)frame CategoryModel:(CategoryDataModel *)model
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
/*****************************************************tableview 属性设置*********************************************************/
        
        if ([self respondsToSelector:@selector(setSeparatorInset:)]) {
            [self setSeparatorInset: UIEdgeInsetsZero];
        }
        if ([self respondsToSelector:@selector(setLayoutMargins:)]) {
            [self setLayoutMargins: UIEdgeInsetsZero];
        }


        //隐藏UITableView的滚动条
        self.showsVerticalScrollIndicator = NO;
    
        
/*****************************************************tableview 属性设置*********************************************************/
        
        
        
        
        headDataArray = [[NSMutableArray alloc]init];
   
        
        self.modelCategory = model;
        self.DataModel = [[NSMutableArray alloc]init];
        NuBerRefreshing = 2;
        self.delegate =self;
        self.dataSource = self;
        UIView *v0 = [[UIView alloc] initWithFrame:CGRectZero];
        [self setTableFooterView:v0];
        
    
        
        //列表请求
        NSDictionary* dicParams1 = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [XSZ_UICommon useridChangUaerdfLoginBoolString],    @"user_id",
                                    @"1",    @"site_id",
                                    self.modelCategory.cate_id,    @"cate_id",
                                    [NSNumber numberWithInteger:1],  @"page_no",
                                    [NSNumber numberWithInteger:20], @"page_size",nil];
        [self RequestURL:dicParams1 tagnuber:1021];

       
        
          __weak typeof(self) weakSelf = self;
        // 添加传统的下拉刷新,设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        [self addLegendHeaderWithRefreshingBlock:^{
           
             [weakSelf RefreshingFantion:1];
        }];
        
        
        //  添加传统的上拉刷新, 进入刷新状态后会自动调用这个block
 
        [self addLegendFooterWithRefreshingBlock:^{
            
            [weakSelf RefreshingFantion:2];
      }];

 
        
        
      //  注册三种类型XIB的id
      CellIdentiferId = @"MomentsViewControllerCellID";
      ModelOneCelliId = @"ModelOneCellID";
      ModelTwoCelliId = @"ModelTwoCellID";
    
    [self registerNib:[UINib nibWithNibName:@"ActivityTableViewCell" bundle:nil] forCellReuseIdentifier:CellIdentiferId];
    [self registerNib:[UINib nibWithNibName:@"ModelOneTableviewCell" bundle:nil] forCellReuseIdentifier:ModelOneCelliId];
    [self registerNib:[UINib nibWithNibName:@"ModelTwoTableViewCell" bundle:nil] forCellReuseIdentifier:ModelTwoCelliId];

        
        
        
         NSDictionary * arrys =  [JsonUtil jsonToDic:model.config];
       
        //判断是否有头广告，用是否含有数据  and  是否含有HeaderParts这个key
        if(model.config.length>0&&[[arrys allKeys] containsObject:@"HeaderParts"])
        {
            //底层headview
            headviewbg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 160)];
            
            
            //headview UIScrollView创建
            headView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 160)];
            headView.delegate =self;
            headView.bounces = NO;
            [headView setPagingEnabled:YES];
            [headView setShowsHorizontalScrollIndicator:NO];
            [headviewbg addSubview:headView];
            
          
            pageControl = [[UIPageControl alloc]initWithFrame:CGRectZero];
            //pageControl.center = CGPointMake(10, 40);
            
            pageControl.backgroundColor = [UIColor redColor];
            [headviewbg addSubview:pageControl];
            
            self.imagelable = [[UILabel alloc]initWithFrame:CGRectZero];
            //imagelable.backgroundColor = [UIColor greenColor];
            self.imagelable.textAlignment = NSTextAlignmentLeft;
            self.imagelable.font = [UIFont systemFontOfSize:14];
            
          
            [headviewbg addSubview:self.imagelable];
            
            
                [self RefreshingFantionHeadView];
        }

    }
    
    
    return self;

}

#pragma mark  HXHttpRequest - Tableview 头图片请求
-(void)RefreshingFantionHeadView
{
//头图片请求
NSDictionary* dicParams_head = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [XSZ_UICommon useridChangUaerdfLoginBoolString],                @"user_id",
                                @"1",                @"site_id",
                                self.modelCategory.cate_id,    @"cate_id",
                                @"Mobile_Home_AD",   @"ad_code",  nil];

if (_httpRequest_head == nil)
{
    _httpRequest_head = [[HXHttpRequest alloc] init];
    _httpRequest_head.delegate = self;
    
    
    
}
[_httpRequest_head requestForParams:dicParams_head andMethod:YZ_LINK_LIST andTag:1023];//@"system.time"];//

}


#pragma mark  HXHttpRequest - Tableview 数据刷新请求  +  数据加载请求
-(void)RefreshingFantion: (NSInteger)nubertag
{
    if(nubertag ==1)
    {
    
        NSDictionary* dicParams1 = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [XSZ_UICommon useridChangUaerdfLoginBoolString],    @"user_id",
                                        @"1",    @"site_id",
                                        self.modelCategory.cate_id,    @"cate_id",
                                        [NSNumber numberWithInteger:1],  @"page_no",
                                        [NSNumber numberWithInteger:20], @"page_size",nil];
        [self RequestURL:dicParams1 tagnuber:1021];
    }else if (nubertag == 2)
    {
        NSDictionary* dicParams1 = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [XSZ_UICommon useridChangUaerdfLoginBoolString],    @"user_id",
                                    @"1",    @"site_id",
                                    self.modelCategory.cate_id,    @"cate_id",
                                    [NSNumber numberWithInteger:NuBerRefreshing],  @"page_no",
                                    [NSNumber numberWithInteger:20], @"page_size",nil];
        [self RequestURL:dicParams1 tagnuber:1022];

    }
  
    
}


#pragma mark-- HXHttpRequest - 数据请求发送
-(void)RequestURL:(NSDictionary *)dicParams tagnuber:(NSInteger)tag
{

    if (_httpRequest == nil)
    {
        _httpRequest = [[HXHttpRequest alloc] init];
        _httpRequest.delegate = self;
        
        
        
    }
    [_httpRequest requestForParams:dicParams andMethod:YZ_ARTICLE_LIST2 andTag:tag];//@"system.time"];//;//@"category.list"];

    
}

#pragma mark  UIScrollView  设置headview上的lable

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView == headView)
    {
        CGFloat pageWith = scrollView.frame.size.width;
        int page = floor((scrollView.contentOffset.x - pageWith/2)/pageWith)+1;
        pageControl.currentPage = page;
        
        NSMutableDictionary *dicb = headDataArray[page];
        
        [self.imagelable removeFromSuperview];
        
  
        self.imagelable = [[UILabel alloc]initWithFrame:CGRectMake(0, self.HighImage-20,Dev_ScreenWidth-40, 20)];
        //imagelable.backgroundColor = [UIColor greenColor];
        self.imagelable.textAlignment = NSTextAlignmentLeft;
        self.imagelable.font = [UIFont systemFontOfSize:14];
        [headviewbg addSubview:self.imagelable];
        
        self.imagelable.text = [dicb objectForKey:@"Title"];
        //[self.tableHeaderView reloadInputViews];
        //[self reloadData];
    }

  
}



#pragma mark - HXHttpRequestDelegate  代理

- (void)requestFinished:(NSString *)responseString andStatusCode:(int)statusCode andTag:(NSInteger)tag
{
    
    
    //停止刷新
    [self.legendHeader endRefreshing];
    [self.legendFooter endRefreshing];
    
    //tableview列表数据
    if(tag == 1021)
    {
        //刷新，可以显示上拉加载数据
        self.footer.hidden = NO;
        
        //在刷新后把页数重置为1
        NuBerRefreshing = 2;
    
        //在刷新后清空上次数据
        [self.DataModel removeAllObjects];
        
        NSDictionary *dic = [[NSDictionary alloc]init];
        dic = [JsonUtil jsonToDic:responseString];
        
        if ([dic[@"data"] isEqual:[NSNull null]])
        {
            return;
        }
        
        NSString * strs = dic[@"data"];
     
        NSDictionary *dics =[JsonUtil jsonToDic:strs];
        
        NSArray *arryy =(NSArray *)dics;
        
        //NSLog(@"-----------> %@",arryy);
        //NSMutableArray *arryData = [[NSMutableArray alloc]init];
        
        for (NSDictionary *dicuu in arryy) {
        
            
            YZCellMassgeModel *cellmodel =[[YZCellMassgeModel alloc]init];
           
            cellmodel.CateId = [dicuu objectForKey:@"CateId"];
            cellmodel.Image = [dicuu objectForKey:@"Image"];
            cellmodel.ReleaseDate= [dicuu objectForKey:@"ReleaseDate"];
            cellmodel.Subtitle = [dicuu objectForKey:@"Subtitle"];
            cellmodel.Summary= [dicuu objectForKey:@"Summary"];
            cellmodel.Title = [dicuu objectForKey:@"Title"];
            cellmodel.id_massge = [dicuu objectForKey:@"id"];

            [self.DataModel addObject:cellmodel];
            
        }
        
      
        [self reloadData];
            
        
        
    }else if (tag == 1022)
    {
        //上拉加载后把页数加一
        NuBerRefreshing = NuBerRefreshing+1;
        
        NSDictionary *dic = [[NSDictionary alloc]init];
        dic = [JsonUtil jsonToDic:responseString];
        NSString * strs = dic[@"data"];
       // NSLog(@"------------------->data %@",dic);
        
        if([strs isEqual:[NSNull null]]||strs.length<=0)
        {
            //如果没有返回数据，表明当前以后的页码已经无数据，可以隐藏上拉加载数据
            self.footer.hidden = YES;
             return;
            
        }else  if([strs isEqualToString:@"[]"])
        {
            //如果没有返回数据，表明当前以后的页码已经无数据，可以隐藏上拉加载数据
            self.footer.hidden = YES;
            return;
            
        }
        
        NSDictionary *dics =[JsonUtil jsonToDic:strs];
        NSArray *arryy =(NSArray *)dics;
      NSLog(@"--------55----------)>  %@",arryy);

        
        for (NSDictionary *dicuu in arryy) {
            
            YZCellMassgeModel *cellmodel =[[YZCellMassgeModel alloc]init];
            
            cellmodel.CateId = [dicuu objectForKey:@"CateId"];
            cellmodel.Image = [dicuu objectForKey:@"Image"];
            cellmodel.ReleaseDate= [dicuu objectForKey:@"ReleaseDate"];
            cellmodel.Subtitle = [dicuu objectForKey:@"Subtitle"];
            cellmodel.Summary= [dicuu objectForKey:@"Summary"];
            cellmodel.Title = [dicuu objectForKey:@"Title"];
            cellmodel.id_massge = [dicuu objectForKey:@"id"];

            [self.DataModel addObject:cellmodel];
            
        }
        
        [self reloadData];
        
        
    }else if (tag == 1023)
    {
     //请求headview
    
        
        
        //头图片请求
        NSDictionary *dic = [[NSDictionary alloc]init];
        dic = [JsonUtil jsonToDic:responseString];
        
        // NSLog(@"---------------->>>> \n%@",dic);
        
        NSString * strs = dic[@"data"];
        NSDictionary *dics =[JsonUtil jsonToDic:strs];
        NSArray *arryy =(NSArray *)dics;
        
        
        //NSLog(@"---------00------->>>> %@",arryy);
        
        for (NSDictionary *dicuu in arryy)
        {
            NSMutableDictionary *dicx = [[NSMutableDictionary alloc]init];
            [dicx setObject:dicuu[@"Title"] forKey:@"Title"];
            [dicx setObject:dicuu[@"Image"] forKey:@"Image"];
            
            [headDataArray addObject:dicx];
        }
        
        if(headDataArray.count>0)
        {
        pageControl.numberOfPages = headDataArray.count;
        }
            for(int i=0;i<headDataArray.count;i++ )
        {
//            UIImageView *imageheadview = [[UIImageView alloc]initWithFrame:CGRectMake(Dev_ScreenWidth*i, 0, Dev_ScreenWidth, 160)];
//            NSMutableDictionary *dicb = headDataArray[i];
//            [imageheadview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",dicb[@"Image"]]] placeholderImage:[UIImage imageNamed:@"bg"]];
//   
//
//            [headView addSubview:imageheadview];
            
            UIImageView *imageheadview = [[UIImageView alloc]initWithFrame:CGRectZero];
            NSMutableDictionary *dicb = headDataArray[i];
            [imageheadview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",dicb[@"Image"]]] placeholderImage:[UIImage imageNamed:@"bg.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    UIImage  *NImage = [self imageCompressForWidth:image targetWidth:Dev_ScreenWidth];
                    self.HighImage = NImage.size.height;
                    
                    headviewbg.frame = CGRectMake(0, 0, Dev_ScreenWidth, NImage.size.height);
                    headView.frame = CGRectMake(0, 0, Dev_ScreenWidth, NImage.size.height);
                    pageControl.frame = CGRectMake(Dev_ScreenWidth-25,NImage.size.height-20, 0, 20);
                    self.imagelable.frame = CGRectMake(0, NImage.size.height-20,Dev_ScreenWidth-40, 20);
                    headView.contentSize = CGSizeMake(Dev_ScreenWidth*headDataArray.count,NImage.size.height);
                    imageheadview.frame = CGRectMake(Dev_ScreenWidth*i, 0, Dev_ScreenWidth, NImage.size.height);
    
                     [headView addSubview:imageheadview];
                    
                    //这里才能添加、因为之前没拿到高度
                     self.tableHeaderView = headviewbg;
                });
                
                
                
            }];
            
            
            
        }
        
        NSMutableDictionary *dicb;
    
        dicb = headDataArray[0];
      
        self.imagelable.text =dicb[@"Title"];

        
        
        [self reloadData];
        
    }


}


#pragma mark  HXHttpRequest - 请求代理，，错误代理
- (void)requestFailed:(NSError *)error andTag:(NSInteger)tag
{
    
    
    
         
}




//指定宽度按比例缩放
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}



#pragma arguments - mark  UITableViewDelegate
// 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.DataModel.count;
}


//设置每行高度（每行高度可以不一样）
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    
  //判断Cell类型
    Cellcellmodel = [self.DataModel objectAtIndex:indexPath.row];
    if([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length<=0)

    {
    
        return 44;
    
    }else if ([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length>0) {
        
       // ModelTwoTableViewCell
        
        
        return 80;
    }
    return 80;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    UITableViewCell *cell;
    
    ActivityTableViewCell  *Activitycell;
    ModelOneTableviewCell  *ModelOnecell;
    ModelTwoTableViewCell  *ModelTwocell;
    
    //判断Cell类型
    Cellcellmodel = [self.DataModel objectAtIndex:indexPath.row];
    
    if([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length<=0)
    {
        ModelOnecell = [tableView dequeueReusableCellWithIdentifier:ModelOneCelliId];
        
        
        
        if (ModelOnecell == nil)
        {
            NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"ModelOneTableviewCell" owner:nil options:nil];
            ModelOnecell = [nibs lastObject];
            ModelOnecell.backgroundColor = [UIColor clearColor];
            
        }
        
        if(self.DataModel.count<1)
        {
            return ModelOnecell;
        }
        Cellcellmodel = [self.DataModel objectAtIndex:indexPath.row];
        
        
        [ModelOnecell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]] placeholderImage:[UIImage imageNamed:@"bg"]];
//         [ModelOnecell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]]];
        
        [ModelOnecell.titleLable setText:Cellcellmodel.Title];
        [ModelOnecell.massgeLable setText:Cellcellmodel.Summary];

        
         return ModelOnecell;
       
    }else if ([Cellcellmodel.Image isEqual:[NSNull null]]&&Cellcellmodel.Summary.length>0) {
        
        ModelTwocell = [tableView dequeueReusableCellWithIdentifier:ModelTwoCelliId];
        
        
        
        if (ModelTwocell == nil)
        {
            NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"ModelTwoTableViewCell" owner:nil options:nil];
            ModelTwocell = [nibs lastObject];
            ModelTwocell.backgroundColor = [UIColor clearColor];
            
        }
        
        if(self.DataModel.count<1)
        {
            return ModelTwocell;
        }
        Cellcellmodel = [self.DataModel objectAtIndex:indexPath.row];
        
        
        [ModelTwocell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]] placeholderImage:[UIImage imageNamed:@"bg"]];
//        [ModelTwocell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]]];
        
        [ModelTwocell.titleLable setText:Cellcellmodel.Title];
        [ModelTwocell.massgeLable setText:Cellcellmodel.Summary];
        
        
        return ModelTwocell;

        
    }else
    {
        Activitycell = [tableView dequeueReusableCellWithIdentifier:CellIdentiferId];
  
        if (Activitycell == nil)
        {
            NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"ActivityTableViewCell" owner:nil options:nil];
            Activitycell = [nibs lastObject];
            Activitycell.backgroundColor = [UIColor clearColor];
            
        }
        
        if(self.DataModel.count<1)
        {
            return Activitycell;
        }
        Cellcellmodel = [self.DataModel objectAtIndex:indexPath.row];
        
        
       
        [Activitycell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]] placeholderImage:[UIImage imageNamed:@"bg"]];
//         [Activitycell.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",Cellcellmodel.Image]]];
        
        [Activitycell.titleLable setText:Cellcellmodel.Title];
        [Activitycell.massgeLable setText:Cellcellmodel.Summary];

        return Activitycell;
        
    }
    
    return cell;
    
}


#pragma mark   Tableview  点击事件代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //去除选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   [self.ListTableviewdelegate PushViewContorllerDataModel: [self.DataModel objectAtIndex:indexPath.row]];
    

}

@end
